import { getCategorydata, getSubcategory, getSubcategoryDetail } from '../../server/category.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories:[],
    categoryData:{},
    currentId:0,
    type:'pop'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getData()
  },
  _getData(){
    this._getCategorydata()
    
  },
  _getCategorydata(){
    getCategorydata().then(res =>{
      
      //1. 获取分类
      const lists = res.data.data.category.list
      //2. 初始化分类数据模型
      const categoryData = {}
      for(let i =0;i<lists.length;i++){
        categoryData[i] = {
          subcategories:[],
          categoryDetails:{
            'pop':[],
            'new':[],
            'sell':[]
          }
        }
      }
      this.setData({
        categories: lists,
        categoryData:categoryData
      })
      //请求第一个类别的数据
      this._getSubcategory(0)
      //初始化请求第一个子类的详情
      this._getSubCategoryDetail(0,'pop')
      this._getSubCategoryDetail(0,'new')
      this._getSubCategoryDetail(0,'sell')
    })
  },

  _getSubcategory(currentId){
    //根据currentId 获得 类别的 maitkey
    const maitkey = this.data.categories[currentId].maitKey
    
    getSubcategory(maitkey).then(res =>{
      const tmpCategorydata = res.data.data.list
      // 动态路径
      const curSubcategory = `categoryData.${currentId}.subcategories`
      // 将获取到的数据填入
     this.setData({
       [curSubcategory]:tmpCategorydata
     })
    })
  },
  _getSubCategoryDetail(currentId,type){
    // 获取第一个子分类miniWallkey
    const miniWallkey = this.data.categories[currentId].miniWallkey
    getSubcategoryDetail(miniWallkey,type).then(res =>{
      const curSubcategoryDetail = `categoryData.${currentId}.categoryDetails.${type}`
      //将获取的数据填入相应的位置
      this.setData({
        [curSubcategoryDetail]:res.data
      })
    
    })
  },
  handleChangeCategory(event){
    const cId = event.detail.currentId
    this.setData({
      currentId:cId
    })
    this._getSubcategory(cId)
    this._getSubCategoryDetail(this.data.currentId,"pop")
    this._getSubCategoryDetail(this.data.currentId,"new")
    this._getSubCategoryDetail(this.data.currentId,"sell")
  },
  handleTabclick(event){
    const currentId = this.data.currentId
    const type = event.detail.type
    this.setData({
      type:type
    })
  }
})